package com.dcivision.dms.core;

import java.io.File;
import java.sql.Connection;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import com.dcivision.dms.bean.DmsLocMaster;
import com.dcivision.dms.dao.DmsLocMasterDAObject;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.mail.core.EmailArchiveClearCacheFile;

public class DmsDocumentClearCache implements Job{
  public static final String REVISION = "$Revision: 1.2.6.1 $";
  private static final Log log = LogFactory.getLog(DmsDocumentClearCache.class);
	public void execute(JobExecutionContext arg0) throws JobExecutionException {
		this.clearZip(arg0);
		EmailArchiveClearCacheFile emailClear = new EmailArchiveClearCacheFile();
		emailClear.clearCacheFile();
	}
	
	public void clearZip(JobExecutionContext arg0) throws JobExecutionException {		
		Connection conn = null;
		try {
      conn = DataSourceFactory.getConnection();
      DmsLocMasterDAObject locMasterDAO = new DmsLocMasterDAObject(null, conn);
      List locMasters = locMasterDAO.getFullList();
      
      for (int i=0; i < locMasters.size(); i++){
      	DmsLocMaster locMaster = (DmsLocMaster)locMasters.get(i);
      	clearZip(arg0,locMaster.getLocPath());
      }

    } catch (Exception e) {
      log.error(e, e);
    } finally {
      try { conn.close(); } catch (Exception ignore) {} finally { conn = null; }
    }
	}
	
	private void clearZip(JobExecutionContext arg0, String path) throws JobExecutionException{
		JobDataMap jobDateMap = arg0.getJobDetail().getJobDataMap();
		String extension = "ZIP";
		if (!Utility.isEmpty(jobDateMap.getString("extension"))){
			extension = jobDateMap.getString("extension");
		}
		
		File file = new File(path);
		String fileList[] = file.list();
		if (fileList == null) return;
		for (int i=0; i < fileList.length; i++){
			if (extension.equals(TextUtility.getExtension(fileList[i]).toUpperCase())){
				String delPath = path + "/" + fileList[i];
				File delFile = new File(delPath);
				delFile.delete();
			}
		}
	}
}
